package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_home

import android.content.Intent
import android.view.Gravity
import android.view.View
import androidx.lifecycle.Observer
import com.anythink.core.api.ATAdInfo
import com.anythink.interstitial.api.ATInterstitial
import com.anythink.nativead.api.ATNativeAdView
import com.anythink.nativead.api.ATNativePrepareExInfo
import com.anythink.nativead.api.ATNativePrepareInfo
import com.app.hubert.guide.NewbieGuide
import com.app.hubert.guide.core.Controller
import com.app.hubert.guide.listener.OnGuideChangedListener
import com.app.hubert.guide.model.GuidePage
import com.app.hubert.guide.model.HighLight
import com.app.hubert.guide.model.HighlightOptions
import com.app.hubert.guide.model.RelativeGuide
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.SelfRenderViewUtil
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdManager
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseFragment
import com.bp.hearthealth.pulse.lnapps.base.bp_liveDataBus.BpLiveDataBus
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.UIHelperBp
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.BpBloodPressureNewRecordActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_blood_pressure.bp_view.BloodPressureViewActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_guide.BpHeartRateGuideActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_heart.bp_list.BpHeartRateHistoryListActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main.BpMainActivity
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.SpUtils
import com.bp.hearthealth.pulse.lnapps.bp_utils.throttleClick
import com.bp.hearthealth.pulse.lnapps.databinding.HomeFragmentBgBinding
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.Timer
import java.util.TimerTask


/**
 * @author isnoam
 * @package_name HomeFragment
 * @description：
 */
class BpHomeFragment : BpBaseFragment<HomeFragmentBgBinding>() {

    private var nativeAd: NativeAd? = null
    private val viewModel: BpHomeViewModel by viewModel()
    private val timer = Timer()
    private var controller: Controller? = null
    private var jump = 0

    override fun loadDataOnce() {
        super.loadDataOnce()
        trackEvent()
        binding.lifecycleOwner = this
        binding.viewModel = viewModel
        (activity as BpMainActivity).baseObserver()
        viewModel.loadHeartRateBean(Constants.USER_ID)
        registerObserver()
        initListener()
        startStopListener()
        showGuide()
        //MTG单一广告测试
//        if (BuildConfig.DEBUG) {
//            MobileAds.openAdInspector(activity) {
//                LogUtil.i("AdInspectorError: $it")
//            }
//        }
    }

    private fun trackEvent() {
        //Health页 第一次展示
        if (!SpUtils.getBoolean("health_first_show")) {
            //第一次展示  health_first_show
            SpUtils.saveBoolean("health_first_show", true)
        }
        //页面展示
        AppsFlyerUtils.trackEvent("health_show")
    }

    private fun startStopListener() {
        timer.schedule(object : TimerTask() {
            override fun run() {
                //首次加载超过3秒不显示
                AdMobNativeAdManager.setNativeAdListener(null)
            }
        }, 3000)
    }

    private fun getAdSwitch() {
        LogUtil.i("开屏广告总开关： ${AdsSwitch.getBoolean(AdsSwitch.adOpenControl)}")
        LogUtil.i("插页广告总开关： ${AdsSwitch.getBoolean(AdsSwitch.adInterControl)}")
        LogUtil.i("原生广告总开关： ${AdsSwitch.getBoolean(AdsSwitch.adNativeControl)}")
        LogUtil.i("激励广告总开关： ${AdsSwitch.getBoolean(AdsSwitch.adRVControl)}")
        LogUtil.i("横幅广告总开关： ${AdsSwitch.getBoolean(AdsSwitch.adBannerControl)}")

        LogUtil.i("用户每日最大广告点击数量： ${AdsSwitch.getUserDailyMaxAdsClickNum()}")
        LogUtil.i("用户每日最大全屏（开屏/插页/激励）广告展示数量： ${AdsSwitch.getUserDailyMaxVideoAdsShowNum()}")

        LogUtil.i("语言选择页屏幕底部_大原生广告位： ${AdsSwitch.getBoolean(AdsSwitch.adNativeLanguage)}")
        LogUtil.i("性别选择页功能栏下方_原生广告： ${AdsSwitch.getBoolean(AdsSwitch.adNativeGender)}")

        LogUtil.i("第一次启动性别选择页后_插页广告： ${AdsSwitch.getBoolean(AdsSwitch.adInterLaunchGender)}")
        LogUtil.i("第一次冷启动后_开屏广告： ${AdsSwitch.getBoolean(AdsSwitch.adOpenLaunch)}")

        LogUtil.i("第一次冷启动后_性别选择页： ${AdsSwitch.getBoolean(AdsSwitch.pageLaunchGender)}")
        LogUtil.i("第一次启动语言选择页后_插页广告： ${AdsSwitch.getBoolean(AdsSwitch.adInterLaunchLanguage)}")
        LogUtil.i("第一次启动引导Guide页后_插页广告： ${AdsSwitch.getBoolean(AdsSwitch.adInterLaunchIntro)}")
        LogUtil.i("血压结果页原生广告位： ${AdsSwitch.getBoolean(AdsSwitch.adNativeBPResult)}")
        LogUtil.i("心率报告页原生广告位： ${AdsSwitch.getBoolean(AdsSwitch.adNativeHRReport)}")
        LogUtil.i("是否缓存插页广告： ${AdsSwitch.getBoolean(AdsSwitch.adInterCacheControl)}")

        LogUtil.i("激励视频解锁倒计时时间： ${AdsSwitch.getBpRvCds()}")
    }

    /**
     * 加载原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadAdmobNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                LogUtil.i("BpHomeFragment onAdLoaded 回调")
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                AppsFlyerUtils.trackEvent("ad_native_health_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_NATIVE_ID, "f66472063a1bb0")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【Health页_原生广告】")
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            setNativeAdView(nativeAdList)
        } else {
            showGuide()
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
//        binding.nativeAdContainer.setNativeAd(nativeAd)
//        binding.nativeAdContainer.visibility = View.VISIBLE
        binding.nativeAdContainerSecond.setNativeAd(nativeAd)
        binding.nativeAdContainerSecond.visibility = View.VISIBLE
        showGuide()
    }

    override fun onResume() {
        super.onResume()
//        getAdSwitch()
//        loadAdmobNativeAd()
//        loadTopOnNativeAd()
        //原生接入后需要删除showGuide()这个方法
        LogUtil.i("BpHomeFragment onResume")
    }

    override fun onVisible() {
        LogUtil.i("BpHomeFragment onVisible")
//        loadAdmobNativeAd()
//        loadTopOnNativeAd()
//        val firstTimeToday = SpUtils.isFirstTimeToday(activity)
//        if (firstTimeToday) {
//            val evaluateDialog = EvaluateDialog(activity)
//            evaluateDialog.showDialog()
//            evaluateDialog.setOnBtnClickLisener(object : EvaluateDialog.OnBtnClickListener {
//                override fun onBtnClick(ratingCount: Int) {
//                    if (ratingCount < 4) {
//                        Toaster.show(R.string._sent_successfully_str)
//                    } else {
//                        GooglePlayUtils.openGooglePlayForRating(activity)
//                    }
//                }
//            })
//        }
//        LogUtil.i("当天第一次：${firstTimeToday}")
    }

    private fun initListener() {
        binding.apply {
            tvMeasusreNow.throttleClick {
                //判断是否第一次打开检测页面
                checkIsFirstOpenDetection()
            }
            tvHeartRateMore.throttleClick {
                startActivity(
                    Intent(
                        activity,
                        BpHeartRateHistoryListActivity::class.java
                    )
                )
            }
            ivArticleFirst.throttleClick {
                (activity as BpMainActivity).startArticleActivity(
                    this@BpHomeFragment.viewModel.firstText.value.toString(),
                    this@BpHomeFragment.viewModel.firstUrl.value!!,
                    Constants.HOME_FRAGMENT_VIEW
                )
            }
            ivArticleSecond.throttleClick {
                (activity as BpMainActivity).startArticleActivity(
                    this@BpHomeFragment.viewModel.secondText.value.toString(),
                    this@BpHomeFragment.viewModel.secondUrl.value!!,
                    Constants.HOME_FRAGMENT_VIEW
                )
            }
            ivArticleThird.throttleClick {
                (activity as BpMainActivity).startArticleActivity(
                    this@BpHomeFragment.viewModel.thirdText.value.toString(),
                    this@BpHomeFragment.viewModel.thirdUrl.value!!,
                    Constants.HOME_FRAGMENT_VIEW
                )
            }
            tvBloodPressure.throttleClick {
                startActivity(
                    Intent(
                        activity,
                        BpBloodPressureNewRecordActivity::class.java
                    )
                )
            }
            tvBloodSugar.throttleClick {
                BpLiveDataBus.with<Int>(Constants.SWITCH_FRAGMENT).postData(1)
            }
            tvPressureMore.throttleClick {
                startActivity(
                    Intent(
                        activity,
                        BloodPressureViewActivity::class.java
                    )
                )
            }
            tvSugarMore.throttleClick {
                BpLiveDataBus.with<Int>(Constants.SWITCH_FRAGMENT).postData(1)
            }
        }
    }


    private fun registerObserver() {
        BpLiveDataBus.with<Boolean>(Constants.CHECK_PERMISSWION).observe(this) {
            checkIsFirstOpenDetection()
        }
        BpLiveDataBus.with<Boolean>(Constants.REFRESH_HEART_RATE).observe(this) {
            viewModel.loadHeartRateBean(Constants.USER_ID)
        }
        BpLiveDataBus.with<Boolean>(AdsSwitch.adAppControl).observe(this) {
            binding.nativeAdContainer.visibility = View.GONE
            binding.nativeAdContainerSecond.visibility = View.GONE
            AdMobNativeAdManager.release()
        }
        viewModel.isFirstOpenDetection.observe(viewLifecycleOwner) { result ->
            if (result) {
                startActivity(Intent(activity, BpHeartRateGuideActivity::class.java))
            } else {
                //校验权限
                (activity as BpMainActivity).requestPermission()
            }
        }
        viewModel.heartRateBean.observe(this, Observer { result ->
            val response = result.getOrNull()
            if (response == null) {
                binding.tvLastRecord.text = UIHelperBp.getString(R.string._last_record_str, "NA")
                return@Observer
            }
            binding.tvLastRecord.text =
                UIHelperBp.getString(R.string._last_record_str, response.number)

        })
    }

    private fun checkIsFirstOpenDetection() {
        viewModel.getIsFirstOpenDetection(Constants.USER_ID)
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).titleBar(binding.toolbar).init()
    }

    private fun showGuide() {
        if (jump != 0) {
            return
        }
        val options: HighlightOptions.Builder = HighlightOptions.Builder()
        options.setOnClickListener {
            if (controller != null) {
                controller!!.remove()
            }
        }
        val build = options.setRelativeGuide(
            RelativeGuide(
                R.layout.blood_pressure_guide_layout,
                Gravity.BOTTOM,
                -UIHelperBp.getDimension(R.dimen.blood_pressure_bottom)
            )
        ).build()
        val page: GuidePage =
            GuidePage.newInstance().addHighLightWithOptions(
                binding.constraintPressure,
                HighLight.Shape.ROUND_RECTANGLE,
                UIHelperBp.getDimension(R.dimen.guide_round),
                0,
                build
            )
        NewbieGuide.with(this).setLabel("blood_pressure").alwaysShow(false).addGuidePage(page)
            .setOnGuideChangedListener(object : OnGuideChangedListener {
                override fun onShowed(controller: Controller?) {
                    this@BpHomeFragment.controller = controller
                }

                override fun onRemoved(controller: Controller?) {
                    this@BpHomeFragment.controller = null
                    if (jump == 0) {
                        jump++
                        startActivity(
                            Intent(
                                activity,
                                BpBloodPressureNewRecordActivity::class.java
                            )
                        )
                    }
                }
            }).build().show()
    }
}